<template>
  <div>
    <div v-loading="loading" class="examiner_box gl_mb_20">
      <el-row :gutter="20">
        <el-col :md="6">
          <p style="font-size: 14px; color: #606266">培训</p>
          <el-select v-model="selectedMes.TrainningId" size="mini" placeholder="请选择" class="select" @change="getTrain()">
            <el-option v-for="item in trainList" :key="item.TrainningId" :label="item.trainningName" :value="item.TrainningId" />
          </el-select>
        </el-col>
        <el-col :md="6">
          <p style="font-size: 14px; color: #606266">考试科目</p>
          <el-select v-model="selectedMes.SubjectId" size="mini" placeholder="请选择" @change="getSubject()">
            <el-option v-for="item in subjectList" :key="item.SubjectId" :label="item.subjectName" :value="item.SubjectId" />
          </el-select>
        </el-col>
        <el-col :md="6">
          <p style="font-size: 14px; color: #606266">查询搜索</p>
          <el-input v-model="selectedMes.Name" suffix-icon="el-icon-search" clearable placeholder="搜索" size="mini" />
        </el-col>
        <el-col :md="6" style="text-align:right;">
          <br>
          <el-button size="mini" type="primary" style="margin-top:8px" @click="toSearch()">查询</el-button>
          <el-button size="mini" type="primary" style="margin-top:8px" @click="toReset()">重置</el-button>
        </el-col>
      </el-row>
    </div>
    <el-row>
      <el-col :md="18">
        <p style="font-size: 14px; color: #606266; margin-bottom: 10px;">成绩录入时间：<span v-if="displayTime">{{ entryTime.scoreRecordStartTime + ' - ' + entryTime.scoreRecordEndTime }}</span></p>
      </el-col>
    </el-row>

    <el-table size="mini" :data="tableData" class="gl_table_noBorder mb_17 resetdate" :header-cell-style="{'text-align':'center'}" style="width: 100%">
      <el-table-column label="序号" type="index" width="50" :index="table_index" />
      <el-table-column label="头像" width="60">
        <template slot-scope="{ row }">
          <div class="gl_mr_10 gl_fl">
            <img class="table_photo" :src="getStaticFileUrl(row.registerImagePath)">
          </div>
        </template>
      </el-table-column>
      <el-table-column label="姓名" prop="registerName" width="70" />
      <el-table-column prop="idCardNumber" label="证件号码" width="90" />
      <el-table-column width="42" align="right">
        <template slot-scope="{ row }">
          <div v-if="row.isOfficial" class="flex_official">官</div>
        </template>
      </el-table-column>
      <el-table-column prop="subjectName" label="科目" align="left" width="110" />
      <el-table-column prop="certificateName" label="证书名称" />
      <el-table-column prop="certificateLevelName" label="证书等级" />
      <el-table-column prop="certificateNumber" label="证书编号" />
      <el-table-column prop="score" label="成绩" width="70">
        <template slot-scope="{ row }">
          <span v-if="!row.isEdit">{{ row.score === 0 ? '' : row.score }}</span>
          <el-input v-else v-model="row.inputScore" size="mini" />
        </template>
      </el-table-column>
      <el-table-column label="审核" width="115" align="center">
        <template slot-scope="{ row }">
          <span v-if="!row.isEdit" style="font-weight:bold">{{ row.approveStatusName }}</span>
          <el-select v-else v-model="row.inputApproveStatusName" size="mini" placeholder="请选择">
            <el-option v-for="item in dict.entryScoreApproveStatus" :key="item.value" :label="item.value" :value="item.value" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column width="100" label="操作" align="center">
        <template slot-scope="{ row }">
          <div v-if="row.approveStatusCode === 'NotApproved'">
            <el-button v-if="!row.isEdit" size="mini" type="text" @click="clickEidt(row)">审核</el-button>
            <el-button v-if="row.isEdit" size="mini" type="text" @click="clickComplete(row)">完成</el-button>
            <el-button v-if="row.isEdit" size="mini" type="text" @click="clickCancel(row)"><span class="gl_color_error">取消</span></el-button>
          </div>
          <div v-else><el-button size="mini" type="text"><span style="color:#606266;">已完成</span></el-button></div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-row style="text-align: right;">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="selectedMes.MaxResultCount"
        :current-page="selectedMes.Page"
        @size-change="changePageSize"
        @current-change="changePage"
      />
    </el-row>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import {
  api_GET_TrainExaminerScoreExaminerTrainningsRegisterId,
  api_GET_TrainExaminerScoreRegisterScores,
  api_GET_TrainExaminerExaminerSettingTrainningId,
  api_POST_TrainExaminerScoreReisterSubjectScoreSubjectEntryId,
  api_PUT_TrainExaminerScoreReisterSubjectScoreSubjectEntryScoreId
} from '@/extend/api/trainswaggerApi/app';
import {
  Api_GET_TrainExaminerScoreRegisterScoresQO,
  SiSTKWTrainReisterSubjectScoreInput
} from '@/lib/form/train/swaggerForm';
export default {
  data () {
    return {
      registerId: '',
      total: 0,
      loading: false,
      selectedMes: new Api_GET_TrainExaminerScoreRegisterScoresQO(),
      changeScore: new SiSTKWTrainReisterSubjectScoreInput(),
      entryTime: {},
      timeStamp: {},
      displayTime: false,
      trainList: [],
      subjectList: [],
      examinerIdList: {},
      allSubject: [],
      tableData: [],
      arr: []
    };
  },
  computed: {
    ...mapState({
      info: state => state.user.info,
      UserType: state => state.user.currentUserType,
      dict: state => state.dict.dict
    }),
    entryScoreApproveStatus: function () {
      const obj = {};
      this.dict.entryScoreApproveStatus.forEach(item => {
        obj[item.value] = item.code;
      });
      return obj;
    }
  },
  watch: {
    'UserType': {
      immediate: true,
      deep: true,
      handler(val) {
        // 获取当前用户角色 Personal : 个人，Delegation：团体， PersonalDelegation：个人 + 团体
        if (val) {
          this.registerId = val.registerId;
          this.getTrainSubjects();
        }
      }
    }
  },
  methods: {
    ...mapActions({
      getCurrentUserType: 'user/getCurrentUserType'
    }),
    // 获取培训科目下的人员
    getCandidate() {
      this.tableData = [];
      this.selectedMes.ExaminerId = this.examinerIdList[this.selectedMes.TrainningId];
      if (this.selectedMes.TrainningId === '' || this.selectedMes.ExaminerId === '') return;
      this.loading = true;
      this.selectedMes.SkipCount = (this.selectedMes.Page - 1) * this.selectedMes.MaxResultCount;
      api_GET_TrainExaminerScoreRegisterScores(this.selectedMes).then(res => {
        this.total = res.totalCount;
        this.loading = false;
        if (res.items && res.items.length > 0) {
          this.tableData = res.items.map((item, index) => {
            this.$set(item, 'isEdit', false);
            this.$set(item, 'isOfficial', false);
            item.score = item.score === 0 ? '' : item.score;
            item.approveStatusCode = item.approveStatusCode === null ? 'NotApproved' : item.approveStatusCode;
            item.approveStatusName = item.approveStatusName === null ? '待审核' : item.approveStatusName;
            this.subjectList.map(val => {
              if (item.subjectId === val.SubjectId && val.isOfficial === true) {
                item.isOfficial = true;
              }
            });
            return item;
          });
        }
      }, error => {
        this.loading = false;
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    // 获取成绩录入时间
    getEntryTime() {
      if (this.selectedMes.TrainningId === '') return;
      api_GET_TrainExaminerExaminerSettingTrainningId(this.selectedMes.TrainningId).then(res => {
        if (res) {
          this.displayTime = true;
          this.$set(this.entryTime, 'scoreRecordStartTime', res.scoreRecordStartTime.replace('-', '年').replace('-', '月').replace('T', '日 '));
          this.$set(this.entryTime, 'scoreRecordEndTime', res.scoreRecordEndTime.replace('-', '年').replace('-', '月').replace('T', '日 '));
          this.$set(this.timeStamp, 'scoreRecordStartTime', Date.parse(res.scoreRecordStartTime.replace(/-/g, '/').replace('T', ' ')));
          this.$set(this.timeStamp, 'scoreRecordEndTime', Date.parse(res.scoreRecordEndTime.replace(/-/g, '/').replace('T', ' ')));
          const date = new Date().getTime();
          if (date > this.timeStamp.scoreRecordStartTime && date < this.timeStamp.scoreRecordEndTime) {
            this.getCandidate();
          } else {
            this.tableData = [];
            this.total = 0;
          }
        } else {
          this.displayTime = false;
          this.entryTime = {};
          this.tableData = [];
          this.total = 0;
        }
      }, error => {
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    // 获取考官培训科目
    getTrainSubjects() {
      api_GET_TrainExaminerScoreExaminerTrainningsRegisterId(this.registerId).then(res => {
        if (res.length !== 0) {
          this.trainList = [];
          this.allSubject = [];
          res.forEach((item, index) => {
            this.trainList.push({ TrainningId: item.trainningId, trainningName: item.trainningName });
            this.examinerIdList[item.trainningId] = item.examinerId;
            item.examinerTrainningSubjects.forEach((i, inx) => {
              this.allSubject.push({ TrainningId: item.trainningId, SubjectId: i.subjectId, subjectName: i.subjectName, isOfficial: i.isOfficial });
            });
          });
          this.selectedMes.TrainningId = this.trainList[0].TrainningId;
          this.subjectList = this.allSubject.filter((item, index) => {
            if (item.isOfficial) {
              item.subjectName = item.subjectName + '（官）';
            }
            return item.TrainningId === this.selectedMes.TrainningId;
          });
          this.subjectList.unshift({ TrainningId: this.selectedMes.TrainningId, SubjectId: '', subjectName: '全部', isOfficial: false });
          if (this.subjectList === []) return;
          this.selectedMes.SubjectId = this.subjectList[0].SubjectId;
          this.getEntryTime();
        }
      }, error => {
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    // 获取静态图片
    getStaticFileUrl(relativeUrl) {
      if (!relativeUrl) return '';
      return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
    },
    // 分页
    changePage(page) {
      this.selectedMes.Page = page;
      this.getEntryTime();
    },
    changePageSize(pagesize) {
      this.selectedMes.MaxResultCount = pagesize;
      this.getEntryTime();
    },
    table_index(index) {
      return (this.selectedMes.Page - 1) * this.selectedMes.MaxResultCount + index + 1;
    },
    getTrain() {
      this.tableData = [];
      this.subjectList = [];
      this.$set(this.selectedMes, 'SubjectId', '');
      if (this.selectedMes.TrainningId === '') {
        return;
      } else {
        this.subjectList = this.allSubject.filter((item, index) => {
          return item.TrainningId === this.selectedMes.TrainningId;
        });
        this.subjectList.unshift({ TrainningId: this.selectedMes.TrainningId, SubjectId: '', subjectName: '全部', isOfficial: false });
        this.selectedMes.SubjectId = this.subjectList[0].SubjectId;
        this.getEntryTime();
      }
    },
    getSubject() {
      this.getEntryTime();
    },
    toSearch() {
      this.getEntryTime();
    },
    toReset() {
      this.selectedMes.Name = '';
      this.getEntryTime();
    },
    clickEidt (row) {
      row.isEdit = true;
      this.$set(row, 'inputScore', row.score);
      this.$set(row, 'inputApproveStatusName', row.approveStatusName);
    },
    clickCancel (row) {
      row.isEdit = false;
    },
    clickComplete (row) {
      if (row.inputApproveStatusName === '待审核') {
        this.$message({ type: 'warning', message: '抱歉，您还未进行审核，无法提交' });
        return;
      }
      // 获取当前培训下的考官id
      this.changeScore.examinerId = this.examinerIdList[this.selectedMes.TrainningId];
      if (!this.registerId) return;
      this.changeScore.registerId = this.registerId;
      this.changeScore.approveStatusCode = this.entryScoreApproveStatus[row.inputApproveStatusName];
      if (row.inputScore !== '') {
        const regex = new RegExp(/^\d+$/);
        if (!regex.test(row.inputScore)) {
          this.$message({ type: 'warning', message: '请输入正确的成绩信息' });
          return;
        }
      }
      this.changeScore.score = Number(row.inputScore);
      if (row.subjectEntryScoreId === null) {
        api_POST_TrainExaminerScoreReisterSubjectScoreSubjectEntryId(row.subjectEntryId, this.changeScore).then(res => {
          row.isEdit = false;
          this.getEntryTime();
          this.changeScore = new SiSTKWTrainReisterSubjectScoreInput();
        }, error => {
          row.isEdit = false;
          const _msg = error.error.message || error.message;
          this.$message({ type: 'error', message: _msg });
        });
      } else {
        api_PUT_TrainExaminerScoreReisterSubjectScoreSubjectEntryScoreId(row.subjectEntryScoreId, this.changeScore).then(res => {
          row.isEdit = false;
          this.getEntryTime();
          this.changeScore = new SiSTKWTrainReisterSubjectScoreInput();
        }, error => {
          row.isEdit = false;
          const _msg = error.error.message || error.message;
          this.$message({ type: 'error', message: _msg });
        });
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.examiner_box {
  padding: 2px;
  font-size: 16px;
}
.select {
  color: #353434;
}
.table_photo {
    width: 36px;
    height: 36px;
    border-radius: 50%;
    text-align: justify;
}
.flex_official {
  box-sizing: border-box;
  width: 22px;
  height: 22px;
  font-size: 12px;
  text-align: center;
  margin: 0px;
  padding: 0px;
  color: #1990ff;
  border: 1px solid #1990ff;
  border-radius: 50%;
  background-color: #fff;
}
</style>
<style>
.resetdate .el-input__inner {
  padding-left: 5px;
}
</style>
